<template>
  <div v-loading="pageLoading" :class="[ !isInCartRoute ? 'member_center gl_clear gl_mt_20': 'mall_page' ]">
    <!-- 菜单 -->
    <div v-show="!isInCartRoute" class="left_nav_menu">
      <div class="member_info">
        <div class="gl_fl" style="padding: 0 8px 0 8px;">
          <show-avatar
            :src="getStaticFileUrl(currentUserIndInfo && currentUserIndInfo.imagePath)"
            width="62px"
            height="62px"
            shape="circle"
            border="4px solid #93B3F0"
            @click="openPhotoCropper('imagePath')"
          />
        </div>
        <div class="gl_fl">
          <div class="member_name gl_mb_5">{{ currentUserIndInfo && currentUserIndInfo.name }}</div>
          <div class="member_tags">
            <el-tag
              v-for="(item, index) in tagList"
              :key="item.id"
              class="gl_mr_10 gl_mt_5"
              size="mini"
              :closable="tagList.length > 1"
              :type="tagsColorTheme[index]"
              style="height: 21px;line-height: 20px;"
              @close="deleteTag(item)"
            >
              {{ item.registerTagType && item.registerTagType.name }}
            </el-tag>
            <el-tooltip v-if="dict.registerTagType && tagList.length < dict.registerTagType.length" effect="dark" content="点击新增角色标签" placement="right">
              <el-button class="add_tag" size="mini" @click="openEditTags">+</el-button>
            </el-tooltip>
          </div>
        </div>
      </div>
      <div class="nav_menu">
        <ul class="nav_menu_list">
          <template v-for="item in optNavMenu">
            <li v-if="item.isShow" :key="item.code" class="nav_menu_item">
              <div class="nav_title">{{ item.name }}</div>
              <div
                v-for="(jtem, jndex) in item.children"
                :key="jndex"
                class="nav_children"
                :class="jtem.path === $route.meta.activePath || jtem.path === $route.path ? 'active' : ''"
                @click="handleRouter(jtem)"
              >
                <i :class="jtem.icon" class="gl_mr_5" />
                <span>{{ jtem.name }}</span>
              </div>
            </li>
          </template>
        </ul>
      </div>
    </div>
    <!-- 内容 -->
    <div v-if="!isInCartRoute" class="right_content gl_px_15">
      <div class="breadcrumb_title">
        <span style="cursor: pointer;" @click="breadcrumbClick">{{ breadcrumbName.first }}</span>
        <span style="color: #353434;" class="gl_mx_10">/</span>
        <span style="color: #353434;">{{ breadcrumbName.second }}</span>
      </div>
      <router-view :key="1" />
    </div>
    <div v-if="isInCartRoute">
      <router-view :key="2" />
    </div>
    <photo-cropper-dialog
      ref="imagePathPhotoCropper"
      auto-crop-width="200px"
      auto-crop-height="280px"
      :fixed-number="[200, 280]"
      :enlarge="1"
      @photoCropperSave="rightLogoPhotoCropperSave"
    />
    <edit-tags ref="editTags" @refreshPage="getTagList" />
  </div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
import {
  SiSTKWEventsManagementCreateRegisterInput
} from '@/lib/form/game/swaggerForm';
import {
  api_GET_EventsManagementRegisterId,
  api_GET_EventsManagementRegisterTag,
  api_DELETE_EventsManagementRegisterTagId,
  api_PUT_EventsManagementRegisterId
} from '@/extend/api/gameswaggerApi/app';
import {
  api_POST_TrainExaminerScoreIstExaminerRegisterId
} from '@/extend/api/trainswaggerApi/app';
import { api_GET_UsersOrganizationUnit } from '@/extend/api/swaggerApi/identity';
import photoCropperDialog from './components/photoCropperDialog';
import editTags from './individual/editTags';
import { CopyData } from '@/lib';
export default {
  components: {
    photoCropperDialog,
    editTags
  },
  data() {
    return {
      pageLoading: false,
      createRegisterInput: new SiSTKWEventsManagementCreateRegisterInput(),
      optNavMenu: {
        // 个人信息
        Personal: {
          name: '个人信息',
          code: 'individual',
          isShow: true,
          children: [
            {
              name: '个人主页',
              path: '/myCenter/individual/info',
              icon: 'el-icon-user'
            }
          ]
        },
        // 团体中心
        Delegation: {
          name: '团体中心',
          code: 'team',
          isShow: false,
          children: [
            {
              name: '团体主页',
              path: '/myCenter/team/info',
              icon: 'el-icon-house'
            },
            {
              name: '人员管理',
              path: '/myCenter/team/member',
              icon: 'el-icon-data-analysis'
            }
          ]
        },
        // 消息中心
        Notice: {
          name: '消息中心',
          code: 'notice',
          isShow: true,
          children: [
            {
              name: '系统消息',
              path: '/myCenter/notice/system',
              icon: 'el-icon-message'
            }
          ]
        },
        // 联赛申请
        // LeagueApplication: {
        //   name: '联赛申请',
        //   code: 'leagueApplication',
        //   isShow: true,
        //   children: [
        //     {
        //       name: '联赛申请',
        //       path: '/myCenter/leagueApplication/main',
        //       icon: 'el-icon-medal'
        //     }
        //   ]
        // },
        // 报项中心
        SignUp: {
          name: '报项中心',
          code: 'signUp',
          isShow: true,
          children: [
            {
              name: '报项中心',
              path: '/myCenter/signUp',
              icon: 'el-icon-edit-outline'
            }
            // {
            //   name: '培训报项',
            //   path: '/myCenter/signUp/trainSignUp',
            //   icon: 'el-icon-edit-outline'
            // }
          ]
        },
        // 职业中心
        Authentication: {
          name: '职业中心',
          code: 'authentication',
          isShow: true,
          children: [
            {
              name: '职业中心',
              path: '/myCenter/authentication/main',
              icon: 'el-icon-document-checked'
            }
          ]
        },
        // 培训中心
        Trainning: {
          name: '培训中心',
          code: 'trainning',
          isShow: true,
          children: [
            {
              name: '培训管理',
              path: '/myCenter/trainning/main',
              icon: 'el-icon-document-checked'
            },
            {
              name: '我的证书',
              path: '/myCenter/trainning/certificate',
              icon: 'el-icon-document-checked'
            }
          ]
        },
        // 考试官
        Examiner: {
          name: '考试官',
          code: 'examiner',
          isShow: false,
          children: [
            {
              name: '考试官',
              path: '/myCenter/examiner/main',
              icon: 'el-icon-finished'
            }
          ]
        },
        // 审核中心
        Approval: {
          name: '审核中心',
          code: 'approval',
          isShow: false,
          children: [
            {
              name: '人员审核',
              path: '/myCenter/approval/main',
              icon: 'el-icon-coordinate'
            }
          ]
        },
        // 订单中心
        Order: {
          name: '订单中心',
          code: 'order',
          isShow: true,
          children: [
            {
              name: '订单中心',
              path: '/myCenter/order/main',
              icon: 'el-icon-tickets'
            }
          ]
        },
        // 商城管理
        Mall: {
          name: '商城管理',
          code: 'mall',
          isShow: true,
          children: [
            {
              name: '收货地址',
              path: '/myCenter/mall/address',
              icon: 'el-icon-map-location'
            },
            {
              name: '我的购物车',
              path: '/myCenter/mall/shoppingCart',
              icon: 'el-icon-shopping-cart-2'
            }
          ]
        },
        // 账号设置
        Setting: {
          name: '账号设置',
          code: 'setting',
          isShow: true,
          children: [
            {
              name: '账号设置',
              path: '/myCenter/setting/main',
              icon: 'el-icon-setting'
            }
          ]
        }
      },
      memberInfo: {},
      tagList: [],
      tagsColorTheme: ['primary', 'success', 'info', 'warning'],
      breadcrumbName: {}
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict,
      info: state => state.user.info,
      currentUserType: state => state.user.currentUserType,
      currentUserIndInfo: state => state.user.currentUserIndInfo,
      tags: state => state.user.tags
    }),
    isInCartRoute () {
      return this.$route.path.indexOf('settlement') > -1;
    }
  },
  watch: {
    currentUserType: {
      handler(val) {
        if (!val) return;
        this.getMemberInfo();
        this.getIsExaminer();
        this.initOptNavMenu();
        this.getTagList();
      }
      // immediate: true
    },
    tags: {
      handler(val, old) {
        if (JSON.stringify(val) !== JSON.stringify(old)) {
          this.getTagList();
        }
      }
    },
    $route: {
      handler() {
        this.initBreadcrumb();
      }
    }
  },
  mounted() {
    this.pageLoading = true;
    this.getDict();
    this.initBreadcrumb();
    console.log(this.$route);
    if (this.currentUserType) {
      this.getIsExaminer();
      this.initOptNavMenu();
      this.getMemberInfo();
      this.getTagList();
    }
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    initBreadcrumb() {
      const _path = this.$route.meta.activePath || this.$route.path;
      for (const i in this.optNavMenu) {
        const item = this.optNavMenu[i];
        for (let j = 0; j < item.children.length; j++) {
          const jtem = item.children[j];
          if (jtem.path === _path) {
            this.$set(this.breadcrumbName, 'first', item.name);
            this.$set(this.breadcrumbName, 'firstPath', _path);
            this.$set(this.breadcrumbName, 'second', jtem.name);
            return;
          }
        }
      }
    },
    // 初始化导航
    async initOptNavMenu() {
      /**
       * 团体信息/审核中心的展示
       * (1) 在后台中没有加入机构 - 新账号（可以创建团体）
       * (2) 在后台中加入了机构且有团体会员管理（EventsManagement.Competitions.MembersManagement）权限
      */
      this.$set(this.optNavMenu.Delegation, 'isShow', false);
      this.$set(this.optNavMenu.Approval, 'isShow', false);
      if (this.currentUserType && 'delegationId' in this.currentUserType) {
        const _delegationId = this.currentUserType.delegationId;
        const _info = this.info;
        if (!_delegationId) {
          const currentOrg = await this.getCurrentOrg();
          if (!currentOrg) {
            this.$set(this.optNavMenu.Delegation, 'isShow', true);
            this.$set(this.optNavMenu.Approval, 'isShow', true);
          }
        } else if (_delegationId && _info.permissions.includes('EventsManagement.Competitions.MembersManagement')) {
          this.$set(this.optNavMenu.Delegation, 'isShow', true);
          this.$set(this.optNavMenu.Approval, 'isShow', true);
        }
      }
      // 如果当前为团体主页 - 刚创建完团体，但是没有权限
      if (this.$route.path.indexOf('/myCenter/team/info') > -1 && !this.optNavMenu.Delegation.isShow) {
        // this.$message({ type: 'error', message: '对不起，您没有团体信息管理权限，请联系您的上级机构' }); // 提示时机不正确
        this.$router.push({
          path: '/myCenter/individual/info'
        });
      }
      this.pageLoading = false;
    },
    // 获取当前登录用户是否为考官
    getIsExaminer() {
      if (this.currentUserType && this.currentUserType.registerId) {
        api_POST_TrainExaminerScoreIstExaminerRegisterId(this.currentUserType.registerId).then(res => {
          if (res.length > 0) {
            this.$set(this.optNavMenu.Examiner, 'isShow', true);
          }
        }, error => {
          const _msg = error.error.message || error.message;
          this.$message({ type: 'error', message: _msg });
        });
      }
    },
    getCurrentOrg() {
      return new Promise((resolve, reject) => {
        api_GET_UsersOrganizationUnit().then(res => {
          resolve(res);
        }, error => {
          reject(error);
        });
      });
    },
    // 路由跳转
    handleRouter(menuItem) {
      this.$router.push({
        path: menuItem.path
      });
    },
    // 获取用户信息
    getMemberInfo() {
      if (!this.currentUserType.registerId) return;
      return new Promise((resolve, reject) => {
        api_GET_EventsManagementRegisterId(this.currentUserType.registerId).then(res => {
          this.$store.dispatch('user/getSaveCurrentUserIndInfo', res);
          resolve(res);
        }, error => {
          reject(error);
          this.$message({ type: 'error', message: (error.error && error.error.message || '') });
        });
      });
    },
    openEditTags() {
      this.$refs.editTags.open(this.tagList);
    },
    // 获取个人标签
    getTagList() {
      return new Promise((resolve, reject) => {
        if (!this.currentUserType.registerId) return;
        api_GET_EventsManagementRegisterTag({
          RegisterId: this.currentUserType.registerId,
          IncludeRegisterTagType: true
        }).then(res => {
          this.tagList = res.items || [];
          this.$store.dispatch('user/getSaveCurrentUserTags', this.tagList);
        }, error => {
          this.$message({ type: 'error', message: '获取个人标签失败！' + (error.error && error.error.message || '') });
        });
      });
    },
    // 删除个人标签
    deleteTag(tag) {
      this.$confirm(`您确定要删除【${tag.registerTagType.name}】标签吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api_DELETE_EventsManagementRegisterTagId(tag.id).then(() => {
          this.getTagList();
        }, error => {
          this.$message({ type: 'error', message: '删除失败！' + (error.error && error.error.message || '') });
        });
      });
    },
    openPhotoCropper(code) {
      if (!(this.currentUserType && this.currentUserType.registerId)) {
        this.$message({ type: 'info', message: '请完善您的个人信息！' });
        return;
      }
      this.$refs.imagePathPhotoCropper.open(this.currentUserIndInfo.imagePath);
    },
    rightLogoPhotoCropperSave(fileUrl) {
      CopyData(this.currentUserIndInfo, this.createRegisterInput);
      this.createRegisterInput.imagePath = fileUrl.tempUrl;
      api_PUT_EventsManagementRegisterId(this.currentUserType.registerId, this.createRegisterInput).then(res => {
        this.getMemberInfo().then(res => {
          this.$refs.imagePathPhotoCropper.close();
          this.$message({ type: 'success', message: '头像保存成功' });
        });
      });
    },
    // 获取静态文件
    getStaticFileUrl(relativeUrl) {
      if (relativeUrl) {
        return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
      } else {
        return require('@/assets/images/face_default.png');
      }
    },
    breadcrumbClick() {
      console.log(this.breadcrumbName.firstPath);
      this.$router.push({
        path: this.breadcrumbName.firstPath
      });
    }
  }
};
</script>
<style scoped>
.member_center {
  width: 1200px;
  min-height: calc(100vh - 160px);
  margin: 20px auto 0;
  background: #ffffff;
  box-shadow: 0px 20px 80px 0px rgba(0,0,0,0.10);
  box-sizing: border-box;
  border: 1px solid #dadada;
  border-radius: 8px;
}
.mall_page {
  width: 1200px;
  margin: 0 auto;
}
.member_center .left_nav_menu {
  float: left;
  width: 220px;
  min-height: calc(100vh - 160px);
  border-right: 1px solid #dadada;
  box-sizing: border-box;
}
.member_info {
  display: flex;
  align-items: center;
  min-height: 112px;
  line-height: 100%;
  background: #f8f8f8;
  border-bottom: 1px solid #dadada;
  border-radius: 8px 8px 0 0;
}
.member_info .member_photo {
  width: 62px;
  height: 62px;
  border-radius: 50%;
  border: 4px solid #93B3F0;
  vertical-align: middle;
  margin: 0 8px 0 8px;
}
.member_info .member_name {
  color: #31456C;
  font-size: 18px;
  font-weight: bold;
}
.nav_menu {
  padding: 0 6px;
}
.nav_menu_item {
  padding: 5px;
  padding-left: 16px;
  border-bottom: 1px solid #efefef;
}
.nav_menu_item .nav_title {
  font-size: 14px;
  font-weight: bold;
  color: #353434;
  padding: 10px 0;
}
.nav_menu_item:last-child {
  border: none;
}
.nav_children {
  padding: 6px 0;
  font-size: 14px;
  color: #8C8C8C;
  cursor: pointer;
  transition: all 0.3s ease;
}
.nav_children.active,
.nav_children.active i,
.nav_children:hover,
.nav_children:hover i{
  color: #1890ff;
  font-weight: bold;
}
.right_content {
  float: left;
  width: calc(100% - 220px);
  box-sizing: border-box;
}
.breadcrumb_title {
  font-size: 16px;
  color: #8C8C8C;
  padding: 17px 0 10px;
  border-bottom: 1px solid #b7b1b1;
  margin-bottom: 10px;
  cursor: default;
  font-weight: bold;
}
.add_tag {
  margin-top: 5px;
  height: 21px;
  line-height: 20px;
  padding-top: 0;
  padding-bottom: 0;
  vertical-align: top;
}
</style>
